import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/choosebutton.dart';
import 'package:model_viewer_plus/model_viewer_plus.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/screens/add_schedule_screen.dart';
import 'package:wayofdressing/screens/schedule_screen.dart';
import 'package:wayofdressing/vivo_connect.dart';

class CalenderScreen extends StatefulWidget {
  static final String id = 'calenderscreen';

  @override
  State<CalenderScreen> createState() => _CalenderScreenState();
}

class _CalenderScreenState extends State<CalenderScreen> {
  MenuController menuController = MenuController();
  bool isAddSchedule = false;
  int threeDNumber = 1;
  String todayAiSuggestion = '';
  DateTime now = DateTime.now();
  int day = 0;
  int month = 0;
  bool chooseMonth = false;
  String weekday = '六';
  List days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    day = now.day;
    month = now.month;
    _loadTodayAiSuggestion();
  }

  Future<void> _loadTodayAiSuggestion() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    DateTime now = DateTime.now();
    String currentDateString = '${now.year}-${now.month}-${now.day}';
    String cachedDateString = prefs.getString('cachedDate') ?? '';
    if (currentDateString == cachedDateString) {
      String? savedTodayAiSuggestion =
          prefs.getString('todayAiSuggestion') ?? '';
      if (savedTodayAiSuggestion != '') {
        setState(() {
          todayAiSuggestion = savedTodayAiSuggestion;
        });
      } else {
        _getTodayAiSuggestion(currentDateString);
      }
    }else{
      _getTodayAiSuggestion(currentDateString);
    }
  }

  Future<void> _getTodayAiSuggestion(String currentDateString) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? savedWeather = prefs.getString('weather') ?? '';
    String suggestion = await vivogpt('请根据今天的天气推荐穿搭，三十字以内:$savedWeather');
    setState(() {
      todayAiSuggestion = suggestion;
    });
    prefs.setString('todayAiSuggestion', todayAiSuggestion);
    prefs.setString('cachedDate', currentDateString);
  }

  List<Widget> dayWidget() {
    List<Widget> list1 = [];
    for (int i = 1; i <= days[month - 1]; i++) {
      var cB = chooseButton(
          isActive: day,
          text: '$i',
          listNumber: i,
          onPressed: () {
            setState(() {
              day = i;
              weekday = getWeekday();
            });
          });
      list1.add(cB);
    }
    return list1;
  }

  List<Widget> monthWidget() {
    List<Widget> list1 = [];
    for (int i = 1; i <= 12; i++) {
      var cB = chooseButton(
          isActive: month,
          text: '$i',
          listNumber: i,
          onPressed: () {
            setState(() {
              month = i;
            });
          });
      list1.add(cB);
    }
    return list1;
  }

  String getWeekday() {
    num sumDay = 0;
    for (int i = 1; i < month; i++) {
      sumDay += days[i - 1];
    }
    sumDay += day;
    sumDay %= 7;
    print(sumDay);
    switch (sumDay) {
      case 1:
        return '一';
      case 2:
        return '二';
      case 3:
        return '三';
      case 4:
        return '四';
      case 5:
        return '五';
      case 6:
        return '六';
      default:
        return '七';
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> dayList = dayWidget();
    List<Widget> monthList = monthWidget();
    weekday = getWeekday();
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 100,
        centerTitle: true,
        title: Text(
          '日程',
          style: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontSize: kTopTitleFontSize,
          ),
        ),
        leading: Row(
          children: [
            SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
        actions: [
          MenuAnchor(
            controller: menuController,
            menuChildren: [
              InMenuButton(
                onPressed: () {
                  menuController.close();
                  if (!isAddSchedule)
                    showModalBottomSheet(
                        isScrollControlled: true,
                        context: context,
                        builder: (context) => AddScheduleScreen()).then((_) {
                      setState(() {
                        isAddSchedule = false;
                      });
                    });
                },
                text: '添加日程',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '删除日程',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '添加提醒',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '删除提醒',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '设置',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: const Alignment(-3, 0.4),
              padding: MaterialStateProperty.all(const EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.5),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child: const Icon(
                  Icons.calendar_today_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black,
                ),
              );
            },
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(),
              Row(
                children: [
                  Container(
                    child: TextButton(
                      style: ButtonStyle(
                          padding: MaterialStatePropertyAll(
                            EdgeInsets.all(0),
                          ),
                          shape: MaterialStateProperty.all(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                          ),
                          backgroundColor: chooseMonth
                              ? MaterialStatePropertyAll(Colors.black54)
                              : MaterialStatePropertyAll(Colors.transparent)),
                      onPressed: () {
                        setState(() {
                          chooseMonth = true;
                          day = 1;
                        });
                      },
                      child: Text(
                        '$month',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                          color: chooseMonth ? Colors.white : Colors.black,
                        ),
                      ),
                    ),
                  ),
                  Text(
                    '月',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Container(
                    child: TextButton(
                      style: ButtonStyle(
                          padding: MaterialStatePropertyAll(
                            EdgeInsets.all(0),
                          ),
                          shape: MaterialStateProperty.all(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                          ),
                          backgroundColor: !chooseMonth
                              ? MaterialStatePropertyAll(Colors.black54)
                              : MaterialStatePropertyAll(Colors.transparent)),
                      onPressed: () {
                        setState(() {
                          chooseMonth = false;
                        });
                      },
                      child: Text(
                        '$day',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.bold,
                          color: chooseMonth ? Colors.black : Colors.white,
                        ),
                      ),
                    ),
                  ),
                  Text(
                    '日',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              Text(
                '周' + weekday,
                style: TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(),
            ],
          ),
          Container(
            height: 38,
            margin: EdgeInsets.symmetric(horizontal: 30),
            decoration: BoxDecoration(
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                  spreadRadius: 2, // 阴影扩展半径
                  blurRadius: 5, // 阴影模糊半径
                  offset: Offset(0, 4), // 阴影偏移量
                ),
              ],
              borderRadius: BorderRadius.circular(25),
              color: Colors.white,
            ),
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: chooseMonth ? monthList : dayList,
            ),
          ),
          Expanded(
            flex: 3,
            child: Container(
              margin: EdgeInsets.only(
                left: 30,
                right: 30,
                top: 10,
              ),
              decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                      spreadRadius: 2, // 阴影扩展半径
                      blurRadius: 5, // 阴影模糊半径
                      offset: Offset(0, 5), // 阴影偏移量
                    ),
                  ],
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(25)),
              child: Stack(
                children: [
                  Row(
                    children: [
                      Expanded(
                        flex: 16,
                        child: Container(
                          decoration: BoxDecoration(
                              color: Colors.transparent,
                              borderRadius: BorderRadius.circular(25)),
                          child: Stack(
                            children: <Widget>[
                              Opacity(
                                opacity: threeDNumber == 1 ? 1 : 0,
                                child: IgnorePointer(
                                  ignoring: threeDNumber == 1 ? false : true,
                                  child: ModelViewer(
                                    src: '3dmodels/jeo4.glb',
                                    autoRotate: true,
                                  ),
                                ),
                              ),
                              Opacity(
                                opacity: threeDNumber == 2 ? 1 : 0,
                                child: IgnorePointer(
                                  ignoring: threeDNumber == 2 ? false : true,
                                  child: ModelViewer(
                                    src: '3dmodels/jeo5.glb',
                                    autoRotate: true,
                                  ),
                                ),
                              ),
                              Opacity(
                                opacity: threeDNumber == 3 ? 1 : 0,
                                child: IgnorePointer(
                                  ignoring: threeDNumber == 3 ? false : true,
                                  child: ModelViewer(
                                    src: '3dmodels/jeo6.glb',
                                    autoRotate: true,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 3,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            GestureDetector(
                              onTap: () {
                                setState(() {
                                  if (threeDNumber < 3)
                                    threeDNumber += 1;
                                  else
                                    threeDNumber = 1;
                                });
                              },
                              child: Icon(
                                Icons.play_arrow_rounded,
                                color: Colors.black,
                                size: 50,
                              ),
                            ),
                            TextButton(
                              onPressed: () {},
                              child: Text(
                                '编辑',
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  Positioned(
                    left: 10,
                    top: 10,
                    child: Text(
                      '当日预搭',
                      style: TextStyle(
                          color: Colors.black,
                          fontSize: 18,
                          fontWeight: FontWeight.bold),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                padding: EdgeInsets.all(20),
                margin: EdgeInsets.only(
                  left: 30,
                  right: 30,
                  top: 20,
                ),
                decoration: BoxDecoration(
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                        spreadRadius: 2, // 阴影扩展半径
                        blurRadius: 5, // 阴影模糊半径
                        offset: Offset(0, 5), // 阴影偏移量
                      ),
                    ],
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(25)),
                child: Text(
                  '穿搭建议：\n$todayAiSuggestion',
                  style: TextStyle(color: Colors.black, fontSize: 12),
                ),
              ),
            ],
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.symmetric(vertical: 20, horizontal: 20),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.symmetric(horizontal: 10),
                      decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                              spreadRadius: 2, // 阴影扩展半径
                              blurRadius: 5, // 阴影模糊半径
                              offset: Offset(0, 5), // 阴影偏移量
                            ),
                          ],
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(25)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            '提醒',
                            style: TextStyle(
                                fontSize: 16,
                                color: Colors.black,
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            '7\\19',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.black,
                            ),
                          ),
                          Text(
                            '23:59',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.black,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    child: CalenderBottomButton(
                      onPressed: () {},
                      text: '常用搭配',
                    ),
                  ),
                  Expanded(
                    child: CalenderBottomButton(
                      onPressed: () {
                        showModalBottomSheet(
                            isScrollControlled: true,
                            context: context,
                            builder: (context) => ScheduleScreen());
                      },
                      text: '日程安排',
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class CalenderBottomButton extends StatelessWidget {
  CalenderBottomButton({required this.text, required this.onPressed});

  final String text;
  final void Function() onPressed;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        alignment: Alignment.center,
        margin: EdgeInsets.symmetric(horizontal: 10),
        decoration: BoxDecoration(boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
            spreadRadius: 2, // 阴影扩展半径
            blurRadius: 5, // 阴影模糊半径
            offset: Offset(0, 5), // 阴影偏移量
          ),
        ], color: Colors.white, borderRadius: BorderRadius.circular(25)),
        child: Text(
          text,
          style: TextStyle(
              fontSize: 16, color: Colors.black, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}
